package pers.fulsun.demo.springcloud.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import pers.fulsun.demo.springcloud.Constants;
import pers.fulsun.demo.springcloud.entity.SysSchedule;
import pers.fulsun.demo.springcloud.helper.CronTaskRegistrar;
import pers.fulsun.demo.springcloud.helper.SchedulingRunnable;
import pers.fulsun.demo.springcloud.service.SysScheduleService;

import java.util.List;

@Slf4j
@Component
public class InitApplication implements ApplicationRunner {


    @Autowired
    private SysScheduleService sysScheduleService;
    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //从数据库获取所有定时任务记录列表
        List<SysSchedule> list = sysScheduleService.list();
        for (SysSchedule sysSchedule : list) {
            //如果定时任务是有效状态，则将定时任务注册到任务列表
            if (sysSchedule.getScheStatus() == Constants.VALID) {
                log.info("注册定时任务：{}", sysSchedule);
                SchedulingRunnable schedulingRunnable = new SchedulingRunnable(sysSchedule.getScheBeanName(), sysSchedule.getScheMethod());
                cronTaskRegistrar.addCronTask(schedulingRunnable, sysSchedule.getScheCron());
            }
        }
    }

}
